package com.open.capacity.course.service.impl;

import com.open.capacity.common.model.Course;
import com.open.capacity.common.model.CourseUser;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.course.dao.CourseUserDao;
import com.open.capacity.course.service.CourseUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CourseUserServiceImpl implements CourseUserService {

    @Autowired
    CourseUserDao courseUserDao;

    @Override
    public Result choice(CourseUser courseUser) {
        boolean isHave = isCourseUser(courseUser.getCourseId(),courseUser.getUsername());
        if (isHave){
            int result = courseUserDao.choice(courseUser);
            return Result.succeed(result == 1 ? "选择成功" : "选择失败");
        }
        return Result.failed("你已经选择过该课程");
    }

    @Override
    public Result update(CourseUser courseUser) {
        int result = courseUserDao.update(courseUser);
        return Result.succeed(result == 1 ? "修改成功" : "修改失败");
    }

    @Override
    public PageResult<CourseUser> getSelectCourseUsers(Map<String, Object> params) {
        int count = courseUserDao.count(params);
        PageUtil.pageParamConver(params,true);
        List<CourseUser> courseUsers = courseUserDao.getSelectCourseUsers(params);
        return PageResult.<CourseUser>builder().code(0).
                data(courseUsers).count((long) count).build();
    }

    private boolean isCourseUser(Integer courseId, String username) {
        int count = courseUserDao.isCourseUser(courseId, username);
        return count == 0 ? true : false;
    }
}
